<template>
  <view class="container">
    <!-- Header -->
    <view class="header">
      <view class="header-content">
        <view class="title">速算选择</view>
        <progress-bar
            :current-step="currentQuestionIndex"
            :show-info="true"
            :total-steps="questions.length"
            label="答题进度"
        ></progress-bar>
      </view>
    </view>

    <!-- Question Area -->
    <view v-if="currentQuestion" class="question-area">
      <view class="question-card">
        <view class="question-number">第 {{ currentQuestionIndex + 1 }} / {{ questions.length }} 题</view>
        <view class="question-text">
          <text class="expression">{{ currentQuestion.question }}</text>
          <text class="equals"> = ?</text>
        </view>
        <view class="question-hint">请选择最接近的答案</view>
      </view>

      <!-- Options -->
      <view class="options-list">
        <view
            v-for="(option, index) in currentQuestion.options"
            :key="index"
            :class="{ 
              'selected': selectedOption === index,
              'correct': showAnswer && index === currentQuestion.correctIndex,
              'wrong': showAnswer && selectedOption === index && index !== currentQuestion.correctIndex
            }"
            class="option-item"
            @tap="selectOption(index)"
        >
          <view class="option-label">{{ String.fromCharCode(65 + index) }}</view>
          <view class="option-value">{{ formatOptionValue(option) }}</view>
          <view v-if="showAnswer && index === currentQuestion.correctIndex" class="option-icon">
            <uni-icons color="#28a745" size="24" type="checkmarkempty"></uni-icons>
          </view>
          <view v-if="showAnswer && selectedOption === index && index !== currentQuestion.correctIndex" class="option-icon">
            <uni-icons color="#dc3545" size="24" type="closeempty"></uni-icons>
          </view>
        </view>
      </view>
    </view>

    <!-- Control Buttons -->
    <view class="controls">
      <button 
        :class="{ 'disabled': selectedOption === null }" 
        :disabled="selectedOption === null" 
        class="control-btn next-btn" 
        @tap="handleNextQuestion"
      >
        <uni-icons color="#ffffff" size="20" :type="currentQuestionIndex === questions.length - 1 ? 'flag' : 'right'"></uni-icons>
        <text>{{ currentQuestionIndex === questions.length - 1 ? '查看结果' : '下一题' }}</text>
      </button>
    </view>
  </view>
</template>

<script>
import SpeedCalcChoiceGenerator from '@/utils/question-generator/question-generator-speed-calc-choice.js';
import ProgressBar from '@/components/common/progress-bar.vue';

export default {
  components: {
    ProgressBar
  },
  data() {
    return {
      questions: [],
      currentQuestionIndex: 0,
      selectedOption: null,
      showAnswer: false,
      startTime: 0,
      questionStartTime: 0,
      isProcessing: false
    }
  },
  computed: {
    currentQuestion() {
      return this.questions[this.currentQuestionIndex];
    }
  },
  onLoad(options) {
    const settings = JSON.parse(decodeURIComponent(options.settings));
    this.startTime = Date.now();
    this.generateQuestions(settings);
    this.questionStartTime = Date.now();
  },
  methods: {
    // 生成题目
    generateQuestions(settings) {
      this.questions = SpeedCalcChoiceGenerator.generateQuestions({
        count: settings.count,
        operations: settings.operations,
        valueTypes: settings.valueTypes,
        optionsCount: settings.options
      });
    },

    // 选择选项
    selectOption(index) {
      if (this.showAnswer || this.isProcessing) return;
      this.selectedOption = index;
    },

    // 格式化选项显示
    formatOptionValue(value) {
      if (typeof value === 'string') return value;
      return value.toString();
    },

    // 处理下一题（合并确认答案和跳转逻辑）
    handleNextQuestion() {
      if (this.selectedOption === null || this.isProcessing) return;
      
      this.isProcessing = true;
      this.showAnswer = true;
      
      const timeUsed = (Date.now() - this.questionStartTime) / 1000;
      
      // 记录答案
      this.questions[this.currentQuestionIndex].userAnswer = this.selectedOption;
      this.questions[this.currentQuestionIndex].isCorrect = this.selectedOption === this.currentQuestion.correctIndex;
      this.questions[this.currentQuestionIndex].timeUsed = timeUsed;

      const isCorrect = this.questions[this.currentQuestionIndex].isCorrect;
      
      // 播放反馈
      if (isCorrect) {
        uni.showToast({
          title: '回答正确！',
          icon: 'success',
          duration: 1200
        });
      } else {
        uni.showToast({
          title: '回答错误',
          icon: 'none',
          duration: 1200
        });
      }

      // 延迟后执行下一步操作
      setTimeout(() => {
        if (this.currentQuestionIndex < this.questions.length - 1) {
          // 跳转到下一题
          this.currentQuestionIndex++;
          this.selectedOption = null;
          this.showAnswer = false;
          this.isProcessing = false;
          this.questionStartTime = Date.now();
        } else {
          // 最后一题，跳转到结果页
          this.submitAllAnswers();
        }
      }, 800);
    },

    // 提交所有答案
    submitAllAnswers() {
      const endTime = Date.now();
      
      // 先设置全局数据，避免异步问题
      getApp().globalData.speedCalcChoiceResult = {
        questions: this.questions,
        startTime: this.startTime,
        endTime: endTime
      };
      
      // 跳转到结果页面
      uni.navigateTo({
        url: `/pages/speed-calc-choice/result`
      });
    }
  }
}
</script>

<style lang="scss" scoped>
.container {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #f5f5f5;
}

.header {
  background: linear-gradient(135deg, #67e8f9, #38bdf8);
  padding: 20rpx 40rpx 30rpx;
  color: white;

  .header-content {
    .title {
      font-size: 36rpx;
      font-weight: bold;
      text-align: center;
      margin-bottom: 20rpx;
    }
  }
}

.question-area {
  flex: 1;
  padding: 40rpx;
}

.question-card {
  background: white;
  border-radius: 20rpx;
  padding: 40rpx;
  margin-bottom: 40rpx;
  box-shadow: 0 5rpx 20rpx rgba(0, 0, 0, 0.1);
  text-align: center;

  .question-number {
    font-size: 24rpx;
    color: #999;
    margin-bottom: 20rpx;
  }

  .question-text {
    font-size: 48rpx;
    font-weight: bold;
    color: #333;
    margin: 30rpx 0;

    .expression {
      color: #38bdf8;
    }

    .equals {
      color: #666;
    }
  }

  .question-hint {
    font-size: 26rpx;
    color: #666;
    margin-top: 20rpx;
  }
}

.options-list {
  .option-item {
    background: white;
    border-radius: 15rpx;
    padding: 30rpx;
    margin-bottom: 20rpx;
    display: flex;
    align-items: center;
    box-shadow: 0 3rpx 10rpx rgba(0, 0, 0, 0.08);
    border: 3rpx solid transparent;
    transition: all 0.3s ease;

    &.selected {
      border-color: #007AFF;
      background-color: #e7f3ff;
      transform: scale(1.02);
    }

    &.correct {
      border-color: #28a745;
      background-color: #d4edda;
    }

    &.wrong {
      border-color: #dc3545;
      background-color: #f8d7da;
    }

    .option-label {
      width: 60rpx;
      height: 60rpx;
      border-radius: 50%;
      background: linear-gradient(135deg, #4facfe, #00f2fe);
      color: white;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 28rpx;
      font-weight: bold;
      margin-right: 20rpx;
    }

    .option-value {
      flex: 1;
      font-size: 36rpx;
      font-weight: bold;
      color: #333;
    }

    .option-icon {
      margin-left: 10rpx;
    }

    &:active {
      transform: scale(0.98);
    }
  }
}

.controls {
  padding: 30rpx 40rpx;
  background: white;
  box-shadow: 0 -3rpx 10rpx rgba(0, 0, 0, 0.1);
}

.control-btn {
  width: 100%;
  height: 80rpx;
  border: none;
  border-radius: 40rpx;
  font-size: 30rpx;
  font-weight: bold;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 10rpx;
  color: white;

  &.next-btn {
    background: linear-gradient(135deg, #67e8f9, #38bdf8);

    &.disabled {
      background: #6c757d;
      opacity: 0.6;
    }
  }

  &:active:not(.disabled) {
    transform: scale(0.98);
  }
}
</style>

